package orderlogic

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"huijing_mall/internal/database"
	"huijing_mall/internal/database/models"
	"huijing_mall/shared/common"
	"huijing_mall/shared/get_ctx_value"
	"huijing_mall/shared/kernel/ask"
	"huijing_mall/shared/kernel/hmErrors"
)

var PaymentMethod = map[string]string{
	"余额支付":  "balance",
	"微信支付":  "wechat",
	"支付宝支付": "alipay",
}

func Orders(c *gin.Context, req ask.OrderReq) {
	dbs := get_ctx_value.GetDBS(c)
	userID := get_ctx_value.GetUID(c)

	//获取id
	var ids []int
	for _, product := range req.Products {
		ids = append(ids, product.ProductsID)
	}

	//通过ID 去查询
	products := database.GetProducts(dbs.DB, ids)

	tx := dbs.DB.Begin()
	//库存改变
	for _, product := range req.Products {
		for i := range products { // 使用索引遍历
			if int(products[i].ID) == product.ProductsID {
				products[i].Stock -= product.Stock
			}
			if products[i].Stock < 0 {
				ask.Errors(c, 400, hmErrors.ErrMsg("库存不足"))
				return
			}
			// 逐条更新（Save 会更新所有字段）
			if err := tx.Save(&products[i]).Error; err != nil {
				tx.Rollback()
				ask.Errors(c, 500, hmErrors.ErrMsg("更新库存失败: "+err.Error()))
				return
			}
		}
	}
	//数据处理
	var items []models.OrderItem
	//for _, product := range products {
	//	items = append(items, models.OrderItem{
	//		OrderID:      0,
	//		ProductID:    product.ID,
	//		ProductName:  "",
	//		ProductImage: nil,
	//		Specs:        nil,
	//		Price:        0,
	//		Quantity:     0,
	//		Subtotal:     0,
	//		Order:        models.Order{},
	//		Product:      models.Product{},
	//	})
	//}
	address := map[string]string{
		"shippingAddress": req.ShippingAddress,
	}
	shippingAddress, _ := json.Marshal(address)
	paymentMethod := PaymentMethod[req.PayMethod]
	//  创建订单
	if err := database.CreateOrder(tx, &models.Order{
		OrderNo:         common.GetRandomString(20),
		UserID:          userID,
		TotalAmount:     req.TotalAmount,
		PaymentAmount:   req.PaymentAmount,
		FreightAmount:   req.FreightAmount,
		DiscountAmount:  req.DiscountAmount,
		CouponID:        &req.CouponID,
		PaymentMethod:   &paymentMethod,
		ShippingAddress: shippingAddress,
		Note:            &req.Note,
		Items:           items,
		User:            database.GetUserInfo(dbs.DB, userID),
	}); err != nil {
		tx.Rollback()
		ask.Errors(c, 500, hmErrors.ErrMsg("创建订单失败"))
		return
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		ask.Errors(c, 500, hmErrors.ErrMsg("提交事务失败"))
		return
	}
	ask.Success(c, "订单创建成功")
	return
}
